package com.java.netty.tcpprotocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //使用客户端发送5条数据
        String mes = "今天天气不错";
        for (int i = 0; i < 15; i++) {
            byte[] content = mes.getBytes(CharsetUtil.UTF_8);
            int length = content.length;
            ctx.writeAndFlush(new MessageProtocol(length, content));
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        System.out.println("客户端接收到信息序号:" + (++this.count));
        System.out.println("客户端接收到信息长度:" + msg.getLen());
        System.out.println("客户端接收到信息内容:" + new String(msg.getContent(), CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常消息" + cause.getMessage());
        ctx.close();
    }
}
